<template>
  <div id="cart">
    <!-- checkbox group -->
    <van-checkbox-group v-model="checksResult" ref="checkBoxGroup">
      <van-cell-group>
        <cart-item
          v-for="item in cartLists"
          :key="item.guid"
          :cart="item.product"
          @choose="onCartItemChoosed"
          @delete="onDelete"
          ref="cart"
        />
      </van-cell-group>
    </van-checkbox-group>

    <!-- 提交订单组件 -->
    <van-submit-bar
      :price="totalPrice"
      button-text="提交订单"
      @submit="onSubmit"
    >
      <van-checkbox v-model="checked" @click="onSelectAll">全选</van-checkbox>
    </van-submit-bar>
  </div>
</template>

<script>
import CartItem from '../components/CartItem'
import { IMAGE_PREFIX } from '../config'
import guid from '../utils/guid'
export default {
  name: 'cart',
  components: {
    'cart-item': CartItem
  },
  data() {
    return {
      // 全选按钮状态
      checked: false,
      checksResult: [],
      // 购物车列表数据
      cartLists: [],
      // 选中的商品对象
      choosedCarts: {
        totalPrice: 0,
        products: []
      }
    }
  },
  methods: {
    // 点击提交订单按钮
    onSubmit() {
      this.$notify({ message: '点击提交订单按钮', type: 'primary' })
    },
    // 点击全选
    onSelectAll() {
      // 获取子组件,调用组件内的方法
      const components = this.$refs.cart
      components.forEach(comp => {
        // 调用购物车组件中被点击的方法
        comp.onCheckBoxClick()
        // 改变购车车条目组件的选中状态
        comp.checked = this.checked
      })
      // 改变 全选 组件的样式
      this.$refs.checkBoxGroup.toggleAll(this.checked)
    },
    // 处理购物车组件传递过来的是否选中的状态
    // obj => {id:xxx,type:true/false, price:xxx}
    onCartItemChoosed(obj) {
      const { id: productId, type, price } = obj
      if (type) {
        this.choosedCarts.products.push(productId)
        this.choosedCarts.totalPrice += parseInt(price)
        console.log(`选中商品id: ${productId}, 价格：${price}`)
      } else {
        this.choosedCarts.products = this.choosedCarts.products.filter(
          item => item !== productId
        )
        this.choosedCarts.totalPrice -= parseInt(price)
        console.log(`id: ${productId} 的商品被取消，价格: ${price}`)
      }
      // console.log(this.choosedCarts)
    },
    /**
     * 业务：获取购物车数据
     */
    getCartData() {
      this.$http
        .get('/shopping_cart/list_cart')
        .then(({ data: resp }) => {
          const { data, meta } = resp
          if (meta.code !== 200) {
            return this.$notify(meta.msg)
          }
          this.cartParser(data)
        })
        .catch(err => {
          console.log(err)
          this.$notify('网络开小差啦...')
        })
    },
    // 数据解析器
    cartParser(rawData) {
      const cartLists = []
      rawData.forEach(item => {
        const productObj = {}
        const { product, productId, quantity, scaleId } = item
        const { image, info, list, name } = product
        const filterList = list.filter(scale => scale.id === scaleId)[0]
        const { price, id: sId } = filterList
        productObj.id = productId
        productObj.name = name
        productObj.desc = info
        productObj.count = quantity
        productObj.thumbnail = IMAGE_PREFIX + image.split(';')[0]
        productObj.price = price
        productObj.scaleId = sId
        cartLists.push({
          product: productObj,
          guid: guid.guid()
        })
      })
      console.log(cartLists)
      this.cartLists = cartLists
    },
    // 捕获到购物车组件删除
    // obj => {id:xxx}
    onDelete(obj) {
      const productId = obj.id
      console.log(`删除购物车商品id：${productId}`)
      this.$http
        .post('/shopping_cart/remove', {
          productId: productId
        })
        .then(({ data: resp }) => {
          const { meta } = resp
          if (meta.code !== 201) {
            return this.$toast.fail(meta.msg)
          }
          // 修改显示购物车数据
          this.cartLists = this.cartLists.filter(
            item => item.product.id !== productId
          )
        })
        .catch(_ => {
          this.$toast.fail('删除商品发生错误,请刷新后再试')
        })
      // console.log(this.cartLists)
    }
  },
  created() {
    this.getCartData()
  },
  computed: {
    // 总价
    totalPrice() {
      return this.choosedCarts.totalPrice
    }
  }
}
</script>

<style lang="less">
#cart {
  width: 100%;
  margin-bottom: 50px;
  .van-checkbox-group {
    width: 100%;
    .van-swipe-cell {
      width: 100%;
    }
  }
  .van-submit-bar {
    position: fixed;
    bottom: 50px;
    left: 0;
  }
}
.delete-button {
  height: 100%;
}
.van-submit-bar__price {
  color: #8b0000;
}
</style>
